var COOKIE_NAME = 'sys_username',
    RET= 2,
    TICKET = '';
$(function () {
    /**
     * 初始化自动登录
     */
    $("#remember").iCheck({
        checkboxClass: 'icheckbox_minimal-blue',
        radioClass: 'iradio_minimal-blue',
        increaseArea: '20%' // optional
    });

    /**
     * cookie查找
     */
    if ($.cookie(COOKIE_NAME)) {
        $("#username").val($.cookie(COOKIE_NAME));
        $("#password").focus();
        $("#remember").iCheck('check');
    } else {
        $("#username").focus();
    }

    /**
     * 表单提交
     */
    $("#login_ok").click(function () {
        if (!validateUsername()) {
            return;
        }
        if (!validatePassword()) {
            return;
        }
        if (!validateCaptcha()) {
            return;
        }


        var $username = $('#username'),
            $password = $('#password');
        var issubmit = true;

        /*var $remember = $("#j_remember");
        if ($remember.attr('checked')) {
            $.cookie(COOKIE_NAME, $("#j_username").val(), {path: '/', expires: 15});
        } else {
            $.cookie(COOKIE_NAME, null, {path: '/'});  //删除cookie
        }
        $("#login_ok").attr("disabled", true).val('登陆中..');
        var password = HMAC_SHA256_MAC($("#j_username").val(), $("#j_password").val());
        $("#j_password").val(HMAC_SHA256_MAC($("#j_randomKey").val(), password));
        window.location.href = 'index.html';
        /!*注意：生产环境时请删除此行*!/
        return false;*/
    });

    $("#captcha").click(function () {
        if (!validateUsername()) {
            return;
        }
        if (!validatePassword()) {
            return;
        }
        var $TencentCaptcha = new TencentCaptcha('2080491045', function (res) {
            RET = res.ret;
            if (res.ret == 0) {
                TICKET = res.ticket;
            } else {
                TICKET = '';
            }
        });
        $TencentCaptcha.show();
    });
});

/**
 * 校验用户
 * @returns {boolean}
 */
function validateUsername() {
    var $username = $('#username');
    if ($.trim($username.val()).length == 0) {
        layer.tips('请输入账号', '#username', {
            tips: [2, '#3595CC']
        });
        $username.focus();
        return false;
    }
    return true;
}

/**
 * 校验密码
 * @returns {boolean}
 */
function validatePassword() {
    var $username = $('#password');
    if ($.trim($username.val()).length == 0) {
        layer.tips('请输入密码', '#password', {
            tips: [2, '#3595CC']
        });
        $username.focus();
        return false;
    }
    return true;
}

/**
 * 验证码验证
 * @returns {boolean}
 */
function validateCaptcha() {
    if (RET == 2 || $.trim(TICKET).length == 0) {
        layer.tips('请点击验证', '#captcha', {
            tips: [2, '#3595CC']
        });
        return false;
    }
    return true;
}